import {Component, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {ActivatedRoute, Router} from '@angular/router';
import {PUblicMethod} from '../../services/PUblicMethod';
import {environment} from '../../../environments/environment';
import {StorageService} from '../../services/storage.service';
import {Message} from 'primeng/primeng';
import {EditorComponent} from '../../public/editor/editor.component';
import {FormobjModel} from '../formobj.model';
import {KnowledgeService} from '../knowledge.service';
import {PublicService} from '../../services/public.service';
import {EventBusService} from '../../services/event-bus.service';
import {KlgAssociateOrderTableComponent} from '../public/klg-associate-order-table/klg-associate-order-table.component';
import {SelectAssociateOrderComponent} from '../public/select-associate-order/select-associate-order.component';

@Component({
  selector: 'app-add-basic-info',
  templateUrl: './add-basic-info.component.html',
  styleUrls: ['./add-basic-info.component.scss']
})
export class AddBasicInfoComponent implements OnInit {

    @ViewChild(EditorComponent) editor: EditorComponent;
    @ViewChild(KlgAssociateOrderTableComponent) associatedTable: KlgAssociateOrderTableComponent;
    @ViewChild('selectAssociateOrderComponent') selectAssociateOrderComponent: SelectAssociateOrderComponent;
    controlDiaglog: boolean;
    formTitle = '新增知识';
    myForm: FormGroup;
    formObj: FormobjModel;
    allknowledgeClasssify: Array<object>;
    allClassify: Array<object>;
    allCatalog: Array<object>;
    allApprovals: Array<object>;
    allManages: Array<object>;
    ip: string;
    uploadImageUrl: string;
    message: Message[] = [];
    switchValue: string = '0';
    selectedWorkOrders = [];
    editable: boolean = false;

    constructor(private fb: FormBuilder,
                private router: Router,
                private activedRouter: ActivatedRoute,
                private storageService: StorageService,
                private knowledgeService: KnowledgeService,
                private publicService: PublicService,
                private eventBusService: EventBusService) {
    }

    ngOnInit() {
        this.formObj = new FormobjModel();
        this.initMyForm();
        this.ip = environment.url.management;
        this.uploadImageUrl = `${this.ip}/knowledge/upload`;
        this.controlDiaglog = false;
        this.cretaeKid();
        this.initCreator();
        this.initKnowlageClassify();
        this.getApprovals('');
        this.getManages('');
    }

    initMyForm = () => {
        this.myForm = this.fb.group({
            label: [null, Validators.required],
            title: [null, Validators.required],
            approver_name: [null, Validators.required]
        });
    };

    isFieldValid = (name: string) => {
        return PUblicMethod.isFieldValid(this.myForm, name);
    };

    clearkid = (kid: string) => {
        this.knowledgeService.clearKid(this.formObj.kid).subscribe(res => {
            if(res === '00000')  {
                this.alert('success', '取消成功');
                window.setTimeout(() => {
                   this.returnOverview();
                }, 1100);
            };
            (!(res === '00000')) && (this.alert('error', `取消失败 + ${res}`));
        });
    };

    goBack = () => {
        this.returnOverview();
        // (!this.formObj.status) && (this.clearkid(this.formObj.kid));
        // (this.formObj.status) && (this.returnOverview());
    };

    returnOverview = () => {
        this.router.navigate(['../klgmanageoverview'], {relativeTo: this.activedRouter});
    };

    openEquipList() {
        this.controlDiaglog = true;
    }

    dcontrolDialogHandler(event) {
        this.controlDiaglog = event;
    }

    startTimeSelected() {

    }

    onBeforeUpload(event) {
        let token = this.storageService.getToken('token');
        event.formData.append('access_token', token);
    }

    onUpload(event) {
        let xhrRespose = JSON.parse(event.xhr.response);
        if ( xhrRespose['errcode'] && xhrRespose['errcode'] === '00000' ) {
            this.formObj.attachments = xhrRespose['datas'];
            this.message = [];
            this.message.push({severity: 'success', summary: '消息提示', detail: '上传成功'});
        }else {
            this.message = [];
            this.message.push({severity: 'error', summary: '消息提示', detail: `上传失败${xhrRespose.errmsg}`});
        }
    }

    switch = (which) => {
        this.switchValue = which;
    };

    deleteOrder = () => {
        this.formObj.devices = this.deleteArrayItems(this.formObj.devices, this.associatedTable.selectDeleteItems);
        this.selectedWorkOrders  = this.formObj.devices;
        this.eventBusService.klgdeletedevice.next(this.formObj.devices);
        this.selectAssociateOrderComponent.searchObj.filter_sids = this.changeSelected2Array(this.formObj.devices);
    };

    deleteArrayItems = (array: Array<any>, items: Array<any>) => {
        for (let i = 0; i < items.length; i++ ) {
            const index = array.findIndex(v => {
                return v['sid'] = items[i]['sid'];
            });
            (index > -1) && (this.selectedWorkOrders.splice(index, 1));
        }
        return this.selectedWorkOrders;
    };

    getContent() {
        let topicContent = this.editor.clickHandle();
        if (!topicContent){
            this.alert('error', '请填写知识详速');
            return;
        }
        return topicContent;
    };

    setContent = (content) => {
        this.editor.setContent(content);
    };

    cretaeKid = () => {
        this.knowledgeService.createKid().subscribe(res => {
            (res['errcode'] === '00000') && (this.formObj.kid = res['data']);
            (!(res['errcode'] === '00000')) && (this.alert('error', `创建编号失败+ ${res}`));
        });
    };

    initCreator = () => {
        this.publicService.getUser().subscribe(res => {
            this.formObj.create_name = res['name'];
        });
    };

    initKnowlageClassify = () => {
        this.knowledgeService.getClassifyDatas().subscribe(res => {
            if (res.length) {
                this.allknowledgeClasssify = PUblicMethod.formateDepDropDown(res);
                this.formObj.knowledge_classify = res[0]['name'];
                this.formObj.knowledge_classify_did = res[0]['did'];
                this.initClassify(res[0]['did']);
            }else {
                this.allknowledgeClasssify = [];
                this.formObj.knowledge_classify_did = '';
                this.formObj.knowledge_classify = '';
            }
        });
    };

    initClassify = father_did => {
        this.knowledgeService.getClassifyDatas(father_did).subscribe(res => {
           if (res.length) {
               this.allClassify = PUblicMethod.formateDepDropDown(res);
               this.formObj.classify = res[0]['name'];
               this.formObj.classify_did = res[0]['did'];
               this.initCatalog(res[0]['did']);
           }else {
               this.allClassify = [];
               this.formObj.classify = '';
               this.formObj.catalog_did = '';
               this.allCatalog = [];
               this.formObj.catalog = '';
               this.formObj.catalog_did = '';
           }
           if (!this.editable){
               this.getQueryParam();
           }
        });
    };

    initCatalog = father_did => {
        this.knowledgeService.getClassifyDatas(father_did).subscribe(res => {
            if (res.length) {
                this.allCatalog = PUblicMethod.formateDepDropDown(res);
                this.formObj.catalog = res[0]['name'];
                this.formObj.catalog_did = res[0]['did'];
            }else {
                this.allCatalog = [];
                this.formObj.catalog = '';
                this.formObj.catalog_did = '';
            }

        });
    };

    knowledgeClasssifySelected = () => {
        if (typeof this.formObj.knowledge_classify === 'object') {
            this.formObj.knowledge_classify_did = this.formObj.knowledge_classify['did'];
            this.formObj.knowledge_classify = this.formObj.knowledge_classify['name'];
        }
        this.initClassify(this.formObj.knowledge_classify);
    };

    classsifySelected = () => {
        if (typeof this.formObj.classify === 'object') {
            this.formObj.classify_did = this.formObj.classify['did'];
            this.formObj.classify = this.formObj.classify['name'];
        }
        this.initCatalog(this.formObj.classify_did);
    };

    catalogSelected = () => {
        if (typeof this.formObj.catalog === 'object') {
            this.formObj.catalog_did = this.formObj.catalog['did'];
            this.formObj.catalog = this.formObj.catalog['name'];
        }
    };

    getApprovals = (oid?) => {
        this.publicService.getApprovers(oid).subscribe(res => {
            if (!res) {
                this.allApprovals = [];
            }else {
                let newArray = PUblicMethod.formateDepDropDown(res);
                this.allApprovals = newArray;
                this.formObj.approver_pid = newArray[0]['value']['pid'];
                this.formObj.approver_name = newArray[0]['value']['name'];
            }
        });
    };

    getManages = (oid?) => {
        this.publicService.getApprovers(oid).subscribe(res => {
            if (!res) {
                this.allManages = [];
            }else {
                let newArray = PUblicMethod.formateDepDropDown(res);
                this.allManages = newArray;
                this.formObj.manager_pid = newArray[0]['value']['pid'];
                this.formObj.manager_name = newArray[0]['value']['name'];
            }
        });
    };

    addSave = () => {
        this.knowledgeService.saveKnowledage(this.formObj).subscribe(res => {
            if (res === '00000') {
                this.alert('success', '保存成功');
                window.setTimeout(() => {
                    this.returnOverview();
                }, 1100);
            }else {
                this.alert('error', `保存失败 + ${res}`);
            }
        });
    };

    modSave = () => {
        this.knowledgeService.keepSaveKnowledage(this.formObj).subscribe(res => { if (res === '00000') {
            this.alert('success', '保存成功');
            window.setTimeout(() => {
                this.returnOverview();
            }, 1100);
        }else {
            this.alert('error', `保存失败 : ${res}`);
        }
        });
    };

    save = () => {
        this.formObj.content = this.getContent();
        this.formatPerson();
        if (!this.formObj.status){
            this.addSave();
        }else {
            this.modSave();
        }
    };

    submit = () => {
        this.formObj.content = this.getContent();
        this.formatPerson();
        if (this.myForm.valid) {
            if (!this.formObj.status) {
                this.requestNewSubmit();
            }else {
                this.requestEditSubmit();
            }
        }else {
            PUblicMethod.validateAllFormFields(this.myForm);
        }
    };

    formatPerson = () => {
        if (typeof this.formObj.approver_name === 'object') {
           this.formObj.approver_pid = this.formObj.approver_name['pid'];
           this.formObj.approver_name = this.formObj.approver_name['name'];
        }
        if(typeof this.formObj.manager_name === 'object') {
            this.formObj.manager_pid = this.formObj.manager_name['pid'];
            this.formObj.manager_name = this.formObj.manager_name['name'];
        }
    };

    requestNewSubmit = () => {
        this.knowledgeService.submitKnowledage(this.formObj).subscribe(res => {
            if (res === '00000') {
                this.alert('success', '提交成功');
                window.setTimeout(() => {
                    this.returnOverview();
                }, 1100);
            }else {
                this.alert('error', `提交失败 + ${res}`);
            }
        });
    };

    requestEditSubmit = () => {
        this.knowledgeService.submitEditKnowledage(this.formObj).subscribe(res => {
            if (res === '00000') {
                this.alert('success', '提交成功');
                window.setTimeout(() => {
                    this.returnOverview();
                }, 1100);
            }else {
                this.alert('error', `提交失败 + ${res}`);
            }
        });
    };

    alert(type: string = 'success', detail: string) {
        this.message = [];
        this.message.push({severity: type, summary: '消息提示', detail: detail});
    };

    requestKlgMessage = kid => {
        this.knowledgeService.getKlgMessage(kid).subscribe(res => {
            if (res) {
                this.formObj = new FormobjModel(res);
                this.setContent(this.formObj.content);
                if (!this.formObj.classify) {
                    this.allClassify = [];
                    this.allCatalog = [];
                }
                if (!this.formObj.catalog) {
                    this.allCatalog = [];
                }
                if (this.formObj.status) {
                    this.eventBusService.klgFlowCharts.next(this.formObj.status);
                }
            }
        });
    };

    getQueryParam = () => {
        this.activedRouter.queryParams.subscribe(data => {
           if (data['kid']) {
               this.formTitle = '编辑知识';
               this.requestKlgMessage(data['kid']);
               this.editable = true;
           }
        });
    };

    getSelectedWorkOrders = (event) => {
        event.forEach(v => {this.selectedWorkOrders.push(v); });
        this.formObj.devices.push(event);
        this.selectAssociateOrderComponent.searchObj.filter_sids = this.changeSelected2Array(event);
    };

    changeSelected2Array= (data): Array<string> => {
        let filterSid = [];
        data.forEach(v => {
            filterSid.push(v['sid']);
        });
        return filterSid;
    }

}
